package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.woyao.core.model.BusinessCategory;
import com.woyao.core.model.GetBusinessCategoryResponse;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.service.BusinessCategoryService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;

public class FilterBusiness extends AppCompatActivity {
    TextView catgorytitle = null;
    HashMap<String,String> parents = new HashMap<String,String>() ;

    private  String curcategory = "";

    private RecyclerView popList = null;
    LinearLayoutManager mLayoutManager =null;
    private NewFilterAapter mAdapter;

    LinearLayoutManager allLayoutManager = null;
    private RecyclerView alllist = null;
    private TreeAdapter allAdapter;


    Boolean changed = false;
    ProgressDialog progressDialog;

    private  String from = "";
    private SearchView mSearchView;

    private TextView explan ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_filter_business);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        //       ab.setHomeAsUpIndicator(R.drawable.icon_menu); // set a custom icon for the default home button
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout
//        ab.setDisplayShowTitleEnabled(false); // disable the default title element
        this.setTitle("筛选业务");

        popList = (RecyclerView) findViewById(R.id.recyclerBusiness);
        mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        popList.setLayoutManager(mLayoutManager);

        explan =  (TextView) findViewById(R.id.buzz_explan);

        alllist = (RecyclerView) findViewById(R.id.id_category_list);
        allLayoutManager = new LinearLayoutManager(this);
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        TextView roottitle = (TextView) findViewById(R.id.roottitle);

        roottitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                curcategory ="";
                catgorytitle.setText(  "" );
                loadAllData();
            }
        });

        mSearchView = (SearchView) findViewById(R.id.searchView);

        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                loadSearch(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        catgorytitle = (TextView) findViewById(R.id.alltitle);

        Button gobackbtn = (Button) findViewById(R.id.goback);

        gobackbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (parents.get(curcategory ) != null) {
                    curcategory = parents.get(curcategory ) ;
                    catgorytitle.setText(  "" );
                    loadAllData();
                }
            }
        });

        Button nextbtn = (Button) findViewById(R.id.add_next);

        nextbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("result",mAdapter.getSelectionKeyValue() );
                    setResult(666, intent);
                    finish();
            }
        });

        Intent intent = getIntent();
        from = intent.getStringExtra("from");
        if (from.equals("org")){
            setTitle("选择所在行业");
        }else if (from.equals("demand")){
            setTitle("选择合作业务");
        }

        KeyValueList business = (KeyValueList)intent.getExtras().get("business");

        mAdapter = new NewFilterAapter(this, business.getContent(),business.getContent());

        mAdapter.setChangedHandler( new NewFilterAapter.Changed(){
            @Override
            public void dataChanged() {
                changed = true;
            }
        });

        popList.setAdapter(mAdapter);

        loadAllData();

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {


        finish();
        return true;
    }

    private void loadAllData(){

        AsyncTask<Void,Void,GetBusinessCategoryResponse> task =
                new AsyncTask<Void, Void, GetBusinessCategoryResponse>() {
                    @Override
                    protected GetBusinessCategoryResponse doInBackground(Void... params) {
                        BusinessCategoryService svc = ServiceFactory.get(BusinessCategoryService.class);
                        Call<GetBusinessCategoryResponse> responseCall = svc.getChildCategory(curcategory,WoyaoooApplication.userId);
                        try {
                            GetBusinessCategoryResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final GetBusinessCategoryResponse response) {
                        renderAll(response.getCategoryList());
                    }

                    @Override
                    protected void onCancelled() {
                    }
                };
        task.execute();
    }




    private void loadSearch(final String keyword){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();

        AsyncTask<Void,Void,GetBusinessCategoryResponse> task =
                new AsyncTask<Void, Void, GetBusinessCategoryResponse>() {
                    @Override
                    protected GetBusinessCategoryResponse doInBackground(Void... params) {
                        BusinessCategoryService svc = ServiceFactory.get(BusinessCategoryService.class);
                        Call<GetBusinessCategoryResponse> responseCall = svc.searchBusiness(keyword);
                        try {
                            GetBusinessCategoryResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final GetBusinessCategoryResponse response) {
                        progressDialog.dismiss();
                        mSearchView.clearFocus();
                        if ( response == null){
                            Common.showSnack(FilterBusiness.this,explan,"没有搜到结果" );
                        }else {
                            catgorytitle.setText( "["+ keyword + "]搜索" );
                            renderAll(response.getCategoryList());

                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                        mSearchView.clearFocus();
                    }
                };
        task.execute();
    }

    private void renderAll(ArrayList<BusinessCategory> categoryArrayList){

        ArrayList<Map<String,String>> mapList = new ArrayList<>();

        for(BusinessCategory cat : categoryArrayList){
            if (cat.getNo().equals("0") ) continue;
            HashMap<String,String> map = new HashMap<>();
            map.put("no", cat.getNo());
            map.put("name", cat.getName());
            map.put("description", cat.getDescription());
            map.put("childs", cat.getChilds() +"");
            mapList.add(map);
        }
        allAdapter = new TreeAdapter(this,  mapList );

        allAdapter.setChangedHandler(new TreeAdapter.Changed() {
            @Override
            public void itemSelected(Map<String, String> one) {
                mAdapter.AddNewOne( one) ;
                mAdapter.notifyDataSetChanged();
                changed = true;
                Common.showSnack( FilterBusiness.this, alllist, "选择了"+one.get("name") ) ;
            }

            @Override
            public void itemGetChildren(Map<String, String> one) {
                parents.put(one.get("no"), curcategory );
                curcategory = one.get("no");
                catgorytitle.setText( one.get("name") );
                loadAllData();

            }
        });
        alllist.setAdapter(allAdapter);

    }




    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}

